import { _decorator, AnimationComponent, Component, Node, Sprite, SpriteFrame } from 'cc';
import { ResourcesUtil } from '../../ResourcesUtil';
const { ccclass, property } = _decorator;

@ccclass('EnemyFrameController')
export class EnemyFrameController extends Component {

    @property(Boolean)
    UseAtlas: Boolean = false;

    private framSpeed: number = 0;
    private rootPath: string;
    private minIndex: number = 0;
    private maxIndex: number = 1;

    private animSprite: Sprite;
    private curIndex: number = 0;
    private curTime: number = 0;
    private imageName: string = "";

    private isPlayAnim: boolean = false;
    public completeListener: any;

    private isLoop: boolean = false;

    onLoad() {
        this.animSprite = this.node.getComponent(Sprite);
    }

    public UpdateAnimInfo(speed, path, name, min, max, loop) {
        this.framSpeed = speed;
        this.rootPath = path;
        this.minIndex = min;
        this.maxIndex = max;
        this.imageName = name;
        this.curIndex = 0;
        this.isPlayAnim = true;
        this.curTime = 0;
        this.isLoop = loop;
    }

    update(deltaTime: number) {
        if (!this.isPlayAnim) {
            return;
        }
        this.curTime = this.curTime + deltaTime;
        if (this.curTime - this.framSpeed >= 0) {
            this.UpdateFrame();
            this.curTime = 0;
            this.curIndex = this.curIndex + 1;
        }
    }


    public SetSprite(index) {
        if (this.animSprite == null) {
            return;
        }
        this.curIndex = index;
        let anmName = this.imageName + this.curIndex;
        if (this.curIndex >= 10) {
            anmName = this.imageName + "0" + this.curIndex;
        }
        else {
            anmName = this.imageName + "00" + this.curIndex;
        }
        let path = this.rootPath + "/" + anmName;
        if(!this.UseAtlas){
            path += `/spriteFrame`;
        }
        ResourcesUtil.loadSpriteFrame(path).then((spriteFrame: SpriteFrame) => {
            if (this.animSprite) {
                this.animSprite.getComponent(Sprite).spriteFrame = spriteFrame;
            }
        })
    }

    UpdateFrame() {
        if (this.curIndex > this.maxIndex) {
            this.curIndex = this.minIndex;
            if (this.completeListener && !this.isLoop) {
                this.isPlayAnim = false;
                this.completeListener(this.imageName);
                return;
            }
        }
        this.SetSprite(this.curIndex);
    }

}


